'''
模拟 layer1 client
'''
import time
import traceback

# 导入PLCClientInterface
try:
    from abc_client import PLCClientInterface # ./
except:
    try:
        from ..layer1.abc_client import PLCClientInterface # layer2/...
    except:
        from plc_client.layer1.abc_client import PLCClientInterface #




import socket
import struct

def create_ins_tcp_frame(command, data):
    """
    构造FINS TCP数据帧
    command: 命码
    data: 具体数据
    """
    header = b'\x46\x4\x4\x4\x9\x4\x5\x3'  # FINS头
    header += struct.pack('>H', len(data) + 8)  # 包总长度
    header += b'\x0\x0\x0\x0\x0\x0\x0'  # 填节
    header += struct.pack('>H', command)  # 命码
    header += b'\x0\x0' * 2  # 误码
    header += struct.pack('>L', data)  # 具体数据
    return header

def send_ins_tcp(ip, port, frame):
    """
    发送FINS TCP请求
    ip: 目标IP
    port: 端口
    frame: 数据帧
    """
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
        sock.connect((ip, port))
        sock.sendall(frame)
        response = sock.recv(4096)  # 根据响应长度调整
        return response

# 实际使用示例
ip_address = '192.168.1.1.1'
port = 9602
command_code = 2  # 示例命令码
data = 100  # 示例数据

frame = create_ins_tcp_frame(command_code, data)
response = send_ins_tcp(ip_address, port, frame)

# 解析并打印响应，根据FINS协议
print(f"接收到响应: {response.hex()}")



